package tcp

import (
	"sync"

	"log"

	"github.com/pkg/errors"
)

type IManager interface {
	//添加链接
	Add(client *Client)

	Updata(oldId string, client *Client)
	//删除连接
	Remove(conn *Client)
	//根据connID获取链接
	Get(string) (*Client, error)
	//得到当前连接总数
	Len() int
	//清除并终止所有d连接
	ClearConn()
}

type Manager struct {
	connMap  map[string]*Client
	connLock sync.RWMutex
}

func NewManager() *Manager {
	return &Manager{
		connMap: make(map[string]*Client),
	}
}

func (mgr *Manager) Add(client *Client) {
	mgr.connLock.Lock()
	defer mgr.connLock.Unlock()
	mgr.connMap[client.GetId()] = client
	log.Printf("Manager length=%d\n", len(mgr.connMap))
}

func (mgr *Manager) Updata(oldId string, client *Client) {
	mgr.connLock.Lock()
	defer mgr.connLock.Unlock()
	delete(mgr.connMap, oldId)
	mgr.connMap[client.GetId()] = client
}

func (mgr *Manager) Remove(client *Client) {
	mgr.connLock.Lock()
	defer mgr.connLock.Unlock()
	delete(mgr.connMap, client.GetId())
	log.Printf("Manager length=%d\n", len(mgr.connMap))
}

func (mgr *Manager) Get(id string) (*Client, error) {
	mgr.connLock.RLock()
	defer mgr.connLock.RUnlock()

	if client, ok := mgr.connMap[id]; ok {
		return client, nil
	} else {
		return nil, errors.New("Manager id=" + id + " not found")
	}
}

func (mgr *Manager) Len() int {
	return len(mgr.connMap)
}

func (mgr *Manager) ClearConn() {
	mgr.connLock.Lock()
	defer mgr.connLock.Unlock()
	for id, client := range mgr.connMap {
		client.Close()
		delete(mgr.connMap, id)
	}
	log.Printf("Manager cleared all UUIDS %d \n", mgr.Len())
}
